# -*- coding: utf-8 -*-
"""
插件管理器
负责插件的加载、管理和执行
"""

import os
import sys
import importlib
import importlib.util
from typing import Dict, List, Any, Optional
from abc import ABC, abstractmethod


class BasePlugin(ABC):
    """插件基类"""
    
    def __init__(self):
        self.name = self.__class__.__name__.lower().replace('plugin', '')
        self.version = "1.0.0"
        self.description = "无描述"
        self.enabled = True
        
    @abstractmethod
    def execute(self, args: List[str]) -> bool:
        """执行插件功能"""
        pass
        
    def get_help(self) -> str:
        """获取插件帮助信息"""
        return f"{self.name}: {self.description}"


class PluginManager:
    """插件管理器"""
    
    def __init__(self, config_manager):
        """初始化插件管理器"""
        self.config_manager = config_manager
        self.plugins: Dict[str, BasePlugin] = {}
        self.plugin_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'plugins')
        
        # 确保插件目录存在
        if not os.path.exists(self.plugin_dir):
            os.makedirs(self.plugin_dir)
            
    def load_plugins(self):
        """加载所有插件"""
        print("正在加载功能模块...")
        
        # 确保插件目录在Python路径中
        if self.plugin_dir not in sys.path:
            sys.path.insert(0, self.plugin_dir)
            
        loaded_count = 0
        
        # 遍历插件目录
        for filename in os.listdir(self.plugin_dir):
            if filename.endswith('.py') and not filename.startswith('__'):
                plugin_name = filename[:-3]  # 移除.py扩展名
                
                try:
                    # 动态导入插件模块
                    spec = importlib.util.spec_from_file_location(
                        plugin_name, 
                        os.path.join(self.plugin_dir, filename)
                    )
                    module = importlib.util.module_from_spec(spec)
                    spec.loader.exec_module(module)
                    
                    # 查找插件类
                    plugin_class = self._find_plugin_class(module)
                    if plugin_class:
                        plugin_instance = plugin_class()
                        self.plugins[plugin_instance.name] = plugin_instance
                        loaded_count += 1
                        print(f"  ✓ 已加载: {plugin_instance.name}")
                    
                except Exception as e:
                    print(f"  ✗ 加载失败: {plugin_name} - {e}")
                    
        print(f"共加载了 {loaded_count} 个功能模块")
        
    def _find_plugin_class(self, module):
        """在模块中查找插件类"""
        for attr_name in dir(module):
            attr = getattr(module, attr_name)
            if (isinstance(attr, type) and 
                issubclass(attr, BasePlugin) and 
                attr != BasePlugin):
                return attr
        return None
        
    def execute_plugin(self, plugin_name: str, args: List[str]) -> bool:
        """执行指定插件"""
        if plugin_name not in self.plugins:
            return False
            
        plugin = self.plugins[plugin_name]
        
        if not plugin.enabled:
            print(f"插件 '{plugin_name}' 已被禁用")
            return True
            
        try:
            return plugin.execute(args)
        except Exception as e:
            print(f"执行插件 '{plugin_name}' 时出错: {e}")
            return True
            
    def get_loaded_plugins(self) -> Dict[str, BasePlugin]:
        """获取已加载的插件"""
        return self.plugins.copy()
    
    # 兼容旧版本接口：get_plugins -> get_loaded_plugins
    def get_plugins(self) -> Dict[str, BasePlugin]:
        return self.get_loaded_plugins()
        
    def enable_plugin(self, plugin_name: str) -> bool:
        """启用插件"""
        if plugin_name in self.plugins:
            self.plugins[plugin_name].enabled = True
            return True
        return False
        
    def disable_plugin(self, plugin_name: str) -> bool:
        """禁用插件"""
        if plugin_name in self.plugins:
            self.plugins[plugin_name].enabled = False
            return True
        return False
        
    def reload_plugins(self):
        """重新加载所有插件"""
        self.plugins.clear()
        self.load_plugins()